<%@ page language="java" pageEncoding="utf-8" %>
<%@ taglib prefix="auth" uri="http://www.jiyinit.com/authTag"%>
<%@ taglib prefix="dict" uri="http://www.jiyinit.com/dictTag"%>

<link rel="stylesheet" href="${basePath}/plugins/ztree/zTreeStyle/zTreeStyle.css${VERSION}" type="text/css">

<div class="right-container">
    <div class="row">
        <div class="col-sm-4">
            <div class="widget-box widget-color-blue2">
                <div class="widget-header">
                    <h4 class="widget-title lighter smaller">机构树</h4>
                </div>

                <div class="widget-body">
                    <div class="widget-main padding-8">
                        <ul id="tree" class="ztree"></ul>
                        <ul class="list">
                            [ <a id="expandAllBtn" href="#" onclick="return false;">全部展开</a> ]
                            [ <a id="resetBtn" href="#" onclick="return false;">重置</a> ]
                        </ul>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-sm-8">
            <div class="widget-box widget-color-green2">
                <div class="widget-header">
                    <h4 class="widget-title lighter smaller">人员列表</h4>
                </div>
                <div class="widget-body">
                    <div class="widget-main padding-8">
                        <div class="container-select text-left">
					        <div class="search-input">
					            <span>登录名：</span>
					            <input id="loginName" name="loginName" type="text" style="width:80px">
					        </div>
					        <div class="search-input">
					            <span>用户姓名：</span>
					            <input id="userName" name="userName" type="text"  style="width:150px">
					        </div>
					        <div class="search-input">
					            <span>部门名称：</span>
					            <input id="orgName" name="orgName" type="text"  style="width:150px">
					        </div>
                            <div class="search-input">
                                <span>角色：</span>
                                <select name="role" id="role">
                                    <dict:option dictCode="ROLE"  showChoose="true"/>
                                </select>
                            </div>
					
					        <button id="searchBtn" class="btn btn-primary" type="button">
					            <i class="fa fa-search"></i>&nbsp;查询
					        </button>
					    </div>
					    <div class="manage-button text-left">
					        <auth:auth authUrl="user/save">
					            <button id="addBtn" class="btn btn-primary" type="button">
					                <i class="fa fa-plus"></i>&nbsp;新增
					            </button>
					        </auth:auth>
					
					        <auth:auth authUrl="user/modify">
					            <button id="modifyBtn" class="btn btn-primary" type="button">
					                <i class="fa fa-pencil"></i>&nbsp;修改
					            </button>
					        </auth:auth>
					
					        <auth:auth authUrl="user/delete">
					            <button id="deleteBtn" class="btn btn-primary" type="button">
					                <i class="fa fa-trash-o"></i>&nbsp;删除
					            </button>
					        </auth:auth>
					
					        <auth:auth authUrl="user/modifyPassword">
					            <button id="modifyPasswordBtn" class="btn btn-primary" type="button">
					                <i class="fa fa-key"></i>&nbsp;修改密码
					            </button>
					        </auth:auth>
                            <auth:auth authUrl="user/modifySalaryPassword">
					            <button id="modifySalaryPasswordBtn" class="btn btn-primary" type="button">
					                <i class="fa fa-key"></i>&nbsp;修改工资条密码
					            </button>
					        </auth:auth>
                            <auth:auth authUrl="user/initialization">
                                <button id="initBtn" class="btn btn-primary" type="button">
                                    <i class="fa fa-key"></i>&nbsp;初始化数据
                                </button>
                            </auth:auth>
					    </div>
                        
                        
                        
                        
                        <div class="row">
					        <div class="col-xs-12">
					            <table id="grid-table"></table>
					            <div id="grid-pager"></div>
					        </div>
					    </div>
					    
                        <div class="clear"></div>
                        <input type="hidden" id="parentId">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- page specific plugin scripts -->
<script src="${basePath}/plugins/ztree/jquery.ztree.core.js${VERSION}"></script>
<script src="${basePath}/plugins/jqGrid/jquery.jqGrid.min.js${VERSION}"></script>
<script src="${basePath}/plugins/jqGrid/grid.locale-cn.js${VERSION}"></script>
<!-- inline scripts related to this page -->
<script type="text/javascript">

var pageii = null;

var userOrgId;
var userOrgName;

jQuery(function ($) {
  /*  CommonUtils.timeout("#error");*/
    CommonUtils.grid({
        url: "${basePath}/user/findByPage",
        colNames: ['序号','登录名', '用户姓名', '员工工号', '手机号码', '部门名称','显示顺序'/*'创建时间'*/],
        colModel: [
            {name: 'userId', index: 'id', key: true, width: 30, sorttype: "int"},
            {
                name: 'loginName',
                index: 'loginName',
                width: 50
            },
            {
                name: 'userName',
                index: 'userName',
                width: 50
            },
            {
                name: 'userNumber',
                index: 'userNumber',
                width: 50
            },
            {
                name: 'userMobileNo',
                index: 'userMobileNo',
                width: 100
            },
            {
                name: 'orgName',
                index: 'orgName',
                width: 100
            },
            {
                name: 'inOrder',
                index: 'inOrder',
                width: 90
            }
            /*{
                name: 'createTime',
                index: 'createTime',
                width: 90,
                formatter: CommonUtils.formateDate
            }*/
        ],
        jsonReader: {
            root: "rows", page: "currentPage", total: "totalPages",
            records: "totalRecords", repeatitems: false, id: "id"
        }
    });

    $("#searchBtn").click(function () {
        queryUsers();
    });

 /*   $("#userName").keypress(function (e) {
        if (e.which == 13) {
            query();
        }
    });*/

    function queryUsers() {
       // alert("roleId: "+ $('#role').val());
        var queryData = {
            "userName": $.trim($('#userName').val()),
            "loginName": $.trim($('#loginName').val()),
            "orgName": $.trim($('#orgName').val()),
            "orgId": '',
            "roleId": $.trim($('#role').val())
        };

        $("#grid-table").jqGrid("setGridParam",
                {
                    postData: queryData,
                    datatype: 'json'
                }
        ).trigger("reloadGrid", [{page: 1}]);
    };

    $("#addBtn").click("click", function () {
        if ($(window).width() > 800){
            pageii = layer.open({
                title: "新增用户",
                type: 2,
                maxmin: true,
                area: ["800px", "90%"],
                content: ['${basePath}/user/add']
            });
        }
        else{
            pageii = layer.open({
                title: "新增用户",
                type: 2,
                maxmin: true,
                area: ["80%", "90%"],
                content: ['${basePath}/user/add']
            });
        }


    });



    $("#modifyBtn").click("click", function () {

        var rowId = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if (rowId.length > 1 || rowId == "") {
            layer.msg("请选择一行数据进行修改！");
            return;
        }
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        var id = rowData.userId;

        pageii = layer.open({
            title: "修改用户信息",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/user/edit?userId=' + id
        });

    });

    var loading = null;

    $('#deleteBtn').click("click", function () {
        var rowsIds = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if (rowsIds.length <= 0  || rowsIds == "") {
            layer.msg("请至少选择一行数据进行删除！");
            return;
        }
        layer.confirm('是否删除选中数据？',{ icon: 3}, function (index) {
            var userIds = [];
            $(rowsIds).each(function () {
                var rowData = $("#grid-table").jqGrid('getRowData', this);
                userIds.push(rowData.userId);
            });

            $.ajax({
                type: "post",
                data: "userIds=" + userIds,
                url: "${basePath}/user/delete",
                dataType: "json",
                beforeSend:function () {
                    $('#deleteBtn').prop("disabled", true);
                    loading = layer.load(0, {
                        shade: [0.4,'#fff'] //0.4透明度的白色背景
                    });
                },
                success: function (data) {
                    $('#deleteBtn').prop("disabled", false);
                    layer.close(loading);
                    if (data.status == "0") {
                        layer.msg("删除成功！");
                        $("#grid-table").jqGrid().trigger("reloadGrid", [{page: 1}]);
                    }
                    else {
                        layer.alert(data, {
                            icon: 0,
                            skin: 'layui-layer-lan',
                            closeBtn: 0
                        })
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    $('#deleteBtn').prop("disabled", false);
                    layer.close(loading);
                }
            });
            return false;

        });

    });

    $("#modifyPasswordBtn").click("click", function () {
        var rowId = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if (rowId.length > 1 || rowId == "") {
            layer.msg("请选择一行数据进行修改！");
            return;
        }
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        var id = rowData.userId;

        pageii = layer.open({
            title: "修改密码",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/user/toModifyPassword?userId=' + id
        });
    });

    $("#modifySalaryPasswordBtn").click("click", function () {
        var rowId = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if (rowId.length > 1 || rowId == "") {
            layer.msg("请选择一行数据进行修改！");
            return;
        }
        var rowData = $("#grid-table").jqGrid('getRowData', rowId);
        var id = rowData.userId;

        pageii = layer.open({
            title: "修改工资条密码",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/user/toModifySalaryPassword?userId=' + id
        });
    });
});





    var setting = {
        async: {
            enable: true,
            url:"${basePath}/org/getOrgTree",
            autoParam:["id=parentId"],
            otherParam:{"otherParam":"zTreeAsyncTest"},
            dataFilter: filter,
            dataType:"json",
            type: "get"
        },
        callback: {
            beforeAsync: beforeAsync,
            onAsyncSuccess: onAsyncSuccess,
            onAsyncError: onAsyncError,
            onClick: onClick
        }
    };
    var curStatus = "init", curAsyncCount = 0, asyncForAll = false, goAsync = false;
    function filter(treeId, parentNode, childNodes) {
        if (!childNodes) return null;
        var data = childNodes.data;
        for (var i=0, l=childNodes.length; i<l; i++) {
            data[i].name = data[i].name.replace(/\.n/g, '.');
        }
        return data;
    }
    function beforeAsync() {
        curAsyncCount++;
    }
    function onAsyncSuccess(event, treeId, treeNode, msg) {
        curAsyncCount--;
        if (curStatus == "expand") {
            expandNodes(treeNode.children);
        } else if (curStatus == "async") {
            asyncNodes(treeNode.children);
        }

        if (curAsyncCount <= 0) {
            if (curStatus != "init" && curStatus != "") {
                asyncForAll = true;
            }
            curStatus = "";
        }
    }
    function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
        curAsyncCount--;

        if (curAsyncCount <= 0) {
            curStatus = "";
            if (treeNode!=null) asyncForAll = true;
        }
    }
    function expandAll() {
        if (!check()) {
            return;
        }
        var zTree = $.fn.zTree.getZTreeObj("tree");
        if (asyncForAll) {
            zTree.expandAll(true);
        } else {
            expandNodes(zTree.getNodes());
            if (!goAsync) {
                curStatus = "";
            }
        }
    }
    function expandNodes(nodes) {
        if (!nodes) return;
        curStatus = "expand";
        var zTree = $.fn.zTree.getZTreeObj("tree");
        for (var i=0, l=nodes.length; i<l; i++) {
            zTree.expandNode(nodes[i], true, false, false);
            if (nodes[i].isParent && nodes[i].zAsync) {
                expandNodes(nodes[i].children);
            } else {
                goAsync = true;
            }
        }
    }
    function asyncNodes(nodes) {
        if (!nodes) return;
        curStatus = "async";
        var zTree = $.fn.zTree.getZTreeObj("tree");
        for (var i=0, l=nodes.length; i<l; i++) {
            if (nodes[i].isParent && nodes[i].zAsync) {
                asyncNodes(nodes[i].children);
            } else {
                goAsync = true;
                zTree.reAsyncChildNodes(nodes[i], "refresh", true);
            }
        }
    }
    function reset() {
        if (!check()) {
            return;
        }
        asyncForAll = false;
        goAsync = false;
        $.fn.zTree.init($("#tree"), setting);
    }
    function check() {
        if (curAsyncCount > 0) {
            return false;
        }
        return true;
    }
    var orgName = "";
    var orgId = 0;

    var curNode;
    function onClick(event, treeId, treeNode, clickFlag) {
        //query(treeNode.id);
        curNode = treeNode;

        orgName = treeNode.name;
        orgId = treeNode.id;
        userOrgId = treeNode.id;
        userOrgName = treeNode.name;
        $("#grid-table").jqGrid('setGridParam',{
            url: "${basePath}/user/anon/findUsersByOrId",
            postData:{
            	orgId: treeNode.id,
            	"userName":'',
            	"loginName":'',
                "orgName":''
            }, //发送数据
            page:1
        }).trigger("reloadGrid"); //重新载入
        
    }
    function refreshCurNode() {
        if(curNode != null){
            var zTree = $.fn.zTree.getZTreeObj("tree");
            zTree.reAsyncChildNodes(curNode, "refresh", false);
        }
    }

    /**
    *  新增修改成功后回调刷新树
     */
    function refreshOperate(parentId) {
        if(parentId == 0){
            reset();
        }
        if(curNode != null){
            var zTree = $.fn.zTree.getZTreeObj("tree");
            //如果无子节点
            curNode.isParent = true;
            zTree.reAsyncChildNodes(curNode, "refresh", false);
        }
    }

    function refreshDelete() {
        if(curNode != null){
            var zTree = $.fn.zTree.getZTreeObj("tree");
            //如果无子节点
            curNode.isParent = true;
            zTree.reAsyncChildNodes(curNode, "refresh", false);
            zTree.reAsyncChildNodes(curNode.getParentNode(), "refresh", false);
        }
    }

    $(function() {
        $.fn.zTree.init($("#tree"), setting);
        $("#expandAllBtn").bind("click", expandAll);
        $("#resetBtn").bind("click", reset);
        CommonUtils.grid({
            url: "${basePath}/org/getOrgTreeForPage",
            colNames: ['机构ID','机构名称', '创建时间'],
            colModel: [
                {name: 'orgId', key: true, width: 40},
                {name: 'orgName', width: 50 },
                {name: 'createTime', width: 90,formatter: CommonUtils.formateDate }
            ],
            jsonReader: {
                root:"rows", page:"currentPage", total:"totalPages",
                records:"totalRecords", repeatitems:false, id : "resourceId"
            }
        });
    });
    $(window).bind('resize', function () {
        var width = $('.col-sm-8').width();
        $('#grid-table').setGridWidth(width);
    });
    function query(parentId){
        $("#parentId").val(parentId);
        $("#grid-table").jqGrid('setGridParam',{
            url: "${basePath}/org/getOrgTreeForPage",
            postData:{
                parentId: parentId
            }, //发送数据
            page:1
        }).trigger("reloadGrid"); //重新载入
    }
    var pageDialog = null;
    $("#addButton").click("click", function () {
        var parentId = $("#parentId").val();
        if(parentId=='' || parentId==null){
            layer.confirm('是否在根节点添加机构？',{ icon: 3},function (index) {
                pageDialog = layer.open({
                    title: "添加机构",
                    type: 2,
                    area: ["800px", "500px"],
                    content: '${basePath}/org/toOrgAdd?parentId=' + 0
                });
                layer.close(index);
            });
           return;
        }
        pageDialog = layer.open({
         title: "添加机构",
         type: 2,
         area: ["800px", "500px"],
         content: '${basePath}/org/toOrgAdd?parentId=' + parentId
         });
    });
    $("#updateButton").click("click", function () {
        var rowId = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if ((rowId.length > 1 || rowId == "") && orgId == 0) {
            layer.msg("请选择一行数据进行修改！");
            return;
        }

        //不选，默认为选择树节点
        var id;
        if(rowId.length == 0){
            id = orgId;
        } else {
            var rowData = $("#grid-table").jqGrid('getRowData', rowId);
            id = rowData.orgId;
        }

        pageDialog = layer.open({
            title: "修改机构",
            type: 2,
            area: ["800px", "500px"],
            content: '${basePath}/org/toOrgUpdate?orgId=' + id
        });
    });
    $('#deleteButton').click("click", function () {
        var rowsIds = $("#grid-table").jqGrid('getGridParam', 'selarrrow');
        if ((rowsIds.length <= 0  || rowsIds == "") && orgId == 0) {
            layer.msg("请至少选择一行数据进行删除！");
            return;
        }
        //不选，默认为选择树节点
        var orgIds = [];
        if(rowsIds.length == 0){
            orgIds.push(orgId);
        } else {
            $(rowsIds).each(function () {
                var rowData = $("#grid-table").jqGrid('getRowData', this);
                orgIds.push(rowData.orgId);
            });
        }

        //删除校验
        $.ajax({
            type: "post",
            data: "orgIds=" + orgIds,
            url: "${basePath}/org/orgDeleteCheck",
            dataType: "json",
            beforeSend:function () {
                $('#deleteButton').prop("disabled", true);
                loading = layer.load(0, {
                    shade: [0.4,'#fff'] //0.4透明度的白色背景
                });
            },
            success: function (data) {
                $('#deleteButton').prop("disabled", false);
                layer.close(loading);
                if (data.status == "0") {
                    layer.confirm('是否删除选中数据？',{ icon: 3}, function (index) {
                        //删除机构
                        $.ajax({
                            type: "post",
                            data: "orgIds=" + orgIds,
                            url: "${basePath}/org/orgDelete",
                            dataType: "json",
                            beforeSend:function () {
                                $('#deleteBtn').prop("disabled", true);
                                loading = layer.load(0, {
                                    shade: [0.4,'#fff'] //0.4透明度的白色背景
                                });
                            },
                            success: function (data) {
                                $('#deleteBtn').prop("disabled", false);
                                layer.close(loading);
                                if (data.status == "0") {
                                    layer.msg("删除成功！");
                                    $("#grid-table").jqGrid().trigger("reloadGrid", [{page: 1}]);
                                    refreshDelete();
                                }
                                else {
                                    layer.alert(data, {
                                        icon: 0,
                                        skin: 'layui-layer-lan',
                                        closeBtn: 0
                                    })
                                }
                            },
                            error: function(xhr, textStatus, errorThrown) {
                                $('#deleteBtn').prop("disabled", false);
                                layer.close(loading);
                            }
                        });
                        return false;

                    });
                } else {
                    layer.alert("所选机构有子机构不允许删除", {
                        icon: 0,
                        skin: 'layui-layer-lan',
                        closeBtn: 0
                    })
                }
            },
            error: function(xhr, textStatus, errorThrown) {
                $('#deleteButton').prop("disabled", false);
                layer.close(loading);
            }
        });
    });
$('#initBtn').click("click", function () {
    $.ajax({
        type: "post",
        url: "${basePath}/user/initialization",
        dataType: "json",
        beforeSend:function () {
            $('#initBtn').prop("disabled", true);
            loading = layer.load(0, {
                shade: [0.4,'#fff'] //0.4透明度的白色背景
            });
        },
        success: function (data) {
            $('#initBtn').prop("disabled", false);
            layer.close(loading);
            if (data.status == "0") {
                layer.msg("初始化成功！");
                $("#grid-table").jqGrid().trigger("reloadGrid", [{page: 1}]);
            }
            else {
                layer.alert(data, {
                    icon: 0,
                    skin: 'layui-layer-lan',
                    closeBtn: 0
                })
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $('#deleteBtn').prop("disabled", false);
            layer.close(loading);
        }
    });
    return false;

});

</script>
